using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DesktopWidgetApp.Server.Models;
using DesktopWidgetApp.Server.Services;
using Microsoft.AspNetCore.Mvc;

namespace DesktopWidgetApp.Server.API.Controllers
{
    /// <summary>
    /// 团队控制器
    /// 提供团队管理的API端点
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class TeamController : BaseController
    {
        private readonly ITeamService _teamService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="teamService">团队服务</param>
        public TeamController(ITeamService teamService)
        {
            _teamService = teamService;
        }

        /// <summary>
        /// 创建新团队
        /// </summary>
        /// <param name="request">创建团队请求</param>
        /// <returns>创建结果</returns>
        [HttpPost]
        public async Task<ActionResult<Team>> CreateTeam([FromBody] CreateTeamRequest request)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var userId = GetCurrentUserIdOrThrow();
            var (success, message, team) = await _teamService.CreateTeamAsync(request.Name, request.Description, userId);

            if (!success)
            {
                return BadRequest(new { message });
            }

            return CreatedAtAction(nameof(GetTeamById), new { teamId = team.Id }, team);
        }

        /// <summary>
        /// 获取当前用户的团队列表
        /// </summary>
        /// <returns>团队列表</returns>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Team>>> GetUserTeams()
        {
            var userId = GetCurrentUserIdOrThrow();
            var teams = await _teamService.GetUserTeamsAsync(userId);
            return Ok(teams);
        }

        /// <summary>
        /// 获取团队详情
        /// </summary>
        /// <param name="teamId">团队ID</param>
        /// <returns>团队详情</returns>
        [HttpGet("{teamId}")]
        public async Task<ActionResult<Team>> GetTeamById(Guid teamId)
        {
            var userId = GetCurrentUserIdOrThrow();
            var isMember = await _teamService.IsUserInTeamAsync(teamId, userId);

            if (!isMember)
            {
                return Forbid("你不是该团队的成员，无法查看详情");
            }

            var team = await _teamService.GetTeamByIdAsync(teamId);
            if (team == null)
            {
                return NotFound();
            }

            return Ok(team);
        }

        /// <summary>
        /// 更新团队信息
        /// </summary>
        /// <param name="teamId">团队ID</param>
        /// <param name="request">更新请求</param>
        /// <returns>更新结果</returns>
        [HttpPut("{teamId}")]
        public async Task<IActionResult> UpdateTeam(Guid teamId, [FromBody] UpdateTeamRequest request)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var userId = GetCurrentUserIdOrThrow();
            var team = await _teamService.GetTeamByIdAsync(teamId);

            if (team == null)
            {
                return NotFound();
            }

            // 检查权限：只有团队创建者才能更新团队信息
            if (team.CreatorId != userId)
            {
                return Forbid("只有团队创建者才能更新团队信息");
            }

            // 更新团队信息
            team.Name = request.Name;
            team.Description = request.Description;

            var (success, message) = await _teamService.UpdateTeamAsync(team);

            if (!success)
            {
                return BadRequest(new { message });
            }

            return Ok(new { message });
        }

        /// <summary>
        /// 删除团队
        /// </summary>
        /// <param name="teamId">团队ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{teamId}")]
        public async Task<IActionResult> DeleteTeam(Guid teamId)
        {
            var userId = GetCurrentUserIdOrThrow();
            var (success, message) = await _teamService.DeleteTeamAsync(teamId, userId);

            if (!success)
            {
                if (message.Contains("不存在"))
                {
                    return NotFound(new { message });
                }
                else if (message.Contains("只有团队创建者"))
                {
                    return Forbid(message);
                }
                else
                {
                    return BadRequest(new { message });
                }
            }

            return Ok(new { message });
        }

        /// <summary>
        /// 添加团队成员
        /// </summary>
        /// <param name="teamId">团队ID</param>
        /// <param name="request">添加成员请求</param>
        /// <returns>添加结果</returns>
        [HttpPost("{teamId}/members")]
        public async Task<IActionResult> AddTeamMember(Guid teamId, [FromBody] AddTeamMemberRequest request)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var userId = GetCurrentUserIdOrThrow();
            var (success, message) = await _teamService.AddTeamMemberAsync(teamId, request.UserId, request.Role, userId);

            if (!success)
            {
                if (message.Contains("不存在"))
                {
                    return NotFound(new { message });
                }
                else if (message.Contains("权限"))
                {
                    return Forbid(message);
                }
                else
                {
                    return BadRequest(new { message });
                }
            }

            return Ok(new { message });
        }

        /// <summary>
        /// 移除团队成员
        /// </summary>
        /// <param name="teamId">团队ID</param>
        /// <param name="userId">用户ID</param>
        /// <returns>移除结果</returns>
        [HttpDelete("{teamId}/members/{userId}")]
        public async Task<IActionResult> RemoveTeamMember(Guid teamId, Guid userId)
        {
            var requestorId = GetCurrentUserIdOrThrow();
            var (success, message) = await _teamService.RemoveTeamMemberAsync(teamId, userId, requestorId);

            if (!success)
            {
                if (message.Contains("不存在"))
                {
                    return NotFound(new { message });
                }
                else if (message.Contains("权限"))
                {
                    return Forbid(message);
                }
                else
                {
                    return BadRequest(new { message });
                }
            }

            return Ok(new { message });
        }

        /// <summary>
        /// 获取团队成员列表
        /// </summary>
        /// <param name="teamId">团队ID</param>
        /// <returns>团队成员列表</returns>
        [HttpGet("{teamId}/members")]
        public async Task<ActionResult<IEnumerable<TeamMember>>> GetTeamMembers(Guid teamId)
        {
            var userId = GetCurrentUserIdOrThrow();
            var isMember = await _teamService.IsUserInTeamAsync(teamId, userId);

            if (!isMember)
            {
                return Forbid("你不是该团队的成员，无法查看成员列表");
            }

            var members = await _teamService.GetTeamMembersAsync(teamId);
            return Ok(members);
        }

        /// <summary>
        /// 检查用户是否为团队成员
        /// </summary>
        /// <param name="teamId">团队ID</param>
        /// <param name="userId">用户ID</param>
        /// <returns>是否为成员</returns>
        [HttpGet("{teamId}/members/{userId}/check")]
        public async Task<ActionResult<bool>> IsUserInTeam(Guid teamId, Guid userId)
        {
            var requestorId = GetCurrentUserIdOrThrow();
            
            // 检查请求者是否为团队成员或被查询用户
            bool canCheck = requestorId == userId; 
            
            if (!canCheck)
            {
                canCheck = await _teamService.IsUserInTeamAsync(teamId, requestorId);
            }
            
            if (!canCheck)
            {
                return Forbid("你没有权限检查该用户的团队成员身份");
            }
            
            var isMember = await _teamService.IsUserInTeamAsync(teamId, userId);
            return Ok(isMember);
        }
    }

    /// <summary>
    /// 创建团队请求模型
    /// </summary>
    public class CreateTeamRequest
    {
        /// <summary>
        /// 团队名称
        /// </summary>
        [System.ComponentModel.DataAnnotations.Required]
        [System.ComponentModel.DataAnnotations.MaxLength(100)]
        public string Name { get; set; }

        /// <summary>
        /// 团队描述
        /// </summary>
        [System.ComponentModel.DataAnnotations.MaxLength(500)]
        public string Description { get; set; }
    }

    /// <summary>
    /// 更新团队请求模型
    /// </summary>
    public class UpdateTeamRequest
    {
        /// <summary>
        /// 团队名称
        /// </summary>
        [System.ComponentModel.DataAnnotations.Required]
        [System.ComponentModel.DataAnnotations.MaxLength(100)]
        public string Name { get; set; }

        /// <summary>
        /// 团队描述
        /// </summary>
        [System.ComponentModel.DataAnnotations.MaxLength(500)]
        public string Description { get; set; }
    }

    /// <summary>
    /// 添加团队成员请求模型
    /// </summary>
    public class AddTeamMemberRequest
    {
        /// <summary>
        /// 用户ID
        /// </summary>
        [System.ComponentModel.DataAnnotations.Required]
        public Guid UserId { get; set; }

        /// <summary>
        /// 成员角色
        /// </summary>
        [System.ComponentModel.DataAnnotations.Required]
        [System.ComponentModel.DataAnnotations.MaxLength(50)]
        public string Role { get; set; } = "Member";
    }
}